package com.fy.fyspace.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fy.fyspace.common.config.UnsplashConfig;
import com.fy.fyspace.service.UnsplashService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * Unsplash 图片服务实现类
 * 仅提供搜索和获取图片信息的API，图片下载由前端处理
 */
@Service
@Slf4j
public class UnsplashServiceImpl implements UnsplashService {

    private final OkHttpClient client;

    @Resource
    private UnsplashConfig unsplashConfig;

    public UnsplashServiceImpl(UnsplashConfig unsplashConfig) {
        // 配置HTTP客户端
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }

    /**
     * 发送请求并获取响应内容
     *
     * @param request
     * @return
     * @throws IOException
     */
    private String sendRequestAndGetString(Request request) throws IOException {
        int maxRetries = 3;
        int currentRetry = 0;

        while (currentRetry < maxRetries) {
            try {
                Response response = client.newCall(request).execute();
                if (!response.isSuccessful()) {
                    throw new IOException("Unexpected response code: " + response);
                }
                return response.body().string();
            } catch (IOException e) {
                currentRetry++;
                if (currentRetry == maxRetries) {
                    throw e;
                }
                try {
                    Thread.sleep(1000 * currentRetry);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new IOException("Request interrupted", ie);
                }
                log.warn("Retry {} for request to {}", currentRetry, request.url());
            }
        }
        throw new IOException("Failed after " + maxRetries + " retries");
    }

    private JSONObject sendRequest(Request request) throws IOException {
        return JSON.parseObject(sendRequestAndGetString(request));
    }

    /**
     * 搜索图片
     *
     * @param query   搜索关键词
     * @param page    页码
     * @param perPage 每页数量
     * @return
     */
    @Override
    public JSONObject searchPhotos(String query, int page, int perPage) {
        try {
            String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8.toString());
            String url = String.format("%s/search/photos?query=%s&page=%d&per_page=%d&orientation=landscape",
                    unsplashConfig.getBaseUrl(), encodedQuery, page, perPage);
            return sendRequest(new Request.Builder().url(url)
                    .header("Authorization", "Client-ID " + unsplashConfig.getAccessKey()).build());
        } catch (IOException e) {
            log.error("Failed to search photos from Unsplash", e);
            throw new RuntimeException("Failed to search photos: " + e.getMessage());
        }
    }

    /**
     * 获取随机图片
     *
     * @param count 图片数量
     * @return
     */
    @Override
    public JSONArray getRandomPhotos(int count) {
        try {
            String url = String.format("%s/photos/random?count=%d&orientation=landscape",
                    unsplashConfig.getBaseUrl(), count);
            Request request = new Request.Builder()
                    .url(url)
                    .header("Authorization", "Client-ID " + unsplashConfig.getAccessKey())
                    .build();

            String responseBody = sendRequestAndGetString(request);
            return JSON.parseArray(responseBody);
        } catch (IOException e) {
            log.error("Failed to get random photos from Unsplash", e);
            throw new RuntimeException("Failed to get random photos: " + e.getMessage());
        }
    }

    /**
     * 获取图片详情
     *
     * @param photoId 图片ID
     * @return
     */
    @Override
    public JSONObject getPhotoDetails(String photoId) {
        try {
            String url = String.format("%s/photos/%s", unsplashConfig.getBaseUrl(), photoId);
            return sendRequest(new Request.Builder().url(url)
                    .header("Authorization", "Client-ID " + unsplashConfig.getAccessKey()).build());
        } catch (IOException e) {
            log.error("Failed to fetch photo details from Unsplash", e);
            throw new RuntimeException("Failed to fetch photo details: " + e.getMessage());
        }
    }

    /**
     * 获取热门图片
     *
     * @param page    页码
     * @param perPage 每页数量
     * @return
     */
    @Override
    public JSONArray getPopularPhotos(int page, int perPage) {
        try {
            String url = String.format("%s/photos?page=%d&per_page=%d&order_by=popular",
                    unsplashConfig.getBaseUrl(), page, perPage);
            Request request = new Request.Builder()
                    .url(url)
                    .header("Authorization", "Client-ID " + unsplashConfig.getAccessKey())
                    .build();

            String responseBody = sendRequestAndGetString(request);
            return JSON.parseArray(responseBody);
        } catch (IOException e) {
            log.error("Failed to get popular photos from Unsplash", e);
            throw new RuntimeException("Failed to get popular photos: " + e.getMessage());
        }
    }
}